//@author A0086393U
package rightnow.ui.widgets;

import java.net.URL;
import java.util.Observable;
import java.util.Observer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import rightnow.logic.FeedbackProvider;
import rightnow.ui.MainApp;
import rightnow.util.UiUtils;

/**
 * FX-Controller for the FeedbackView.fxml display element. Contains the
 * UI logic for the feedback box. FeedbackController is an Observer, so
 * it can update itself automatically when notified without needing to be
 * passed around the entire program.
 * 
 */
public class FeedbackController extends AnchorPane implements Observer {
	private static final Logger LOG = LoggerFactory.getLogger(MainApp.class);

	private static final String FEEDBACK_VIEW_FXML = "/fxml/FeedbackView.fxml";
	
	/* These are components in this section of the UI, and they will be
	 * injected into by FXML automatically.
	 * 
	 * DO NOT CREATE NEW INSTANCES OF THESE! (unless you know what you are doing)
	 */
	@FXML Label feedbackLabel;
	
	private URL feedbackViewFxmlUrl = getClass().getResource(FEEDBACK_VIEW_FXML);
	
	@FXML
	void initialize() {
		LOG.info("Creating feedback controller");
		
		assert feedbackLabel != null : "fx:id=\"cmdLine\" was not injected";
		LOG.debug("Fxml dependencies successfully injected.");

		LOG.info("Feedback controller successfully created");
	}
	
	public FeedbackController() {
		super();
		
		// Load fxml because ListPresenter is a custom component
		UiUtils.loadFxml(this, this, feedbackViewFxmlUrl);
		
		// Add this as an Observer to QuickHelp and UiFeedback
		QuickHelp.getInstance().addObserver(this);
		FeedbackProvider.getInstance().addObserver(this);
		
		// Set the feedback message to the default
		QuickHelp.getInstance().generateDefaultQuickHelpText();
	}
	
	public void update(Observable obs, Object arg) {
		if (obs == FeedbackProvider.getInstance()) {
			FeedbackProvider fp = FeedbackProvider.getInstance();
			if (fp.hasFeedbackMsgChanged()) {
				LOG.debug("Feedback box updated by Quick Feedback");
				feedbackLabel.setText(FeedbackProvider.getInstance().getFeedbackMessage());
			}
		}
		
		if (obs == QuickHelp.getInstance()) {
			LOG.debug("Feedback box updated by Quick Help");
			feedbackLabel.setText(QuickHelp.getInstance().getMessage());
		}
	}

	/**
	 * Generates and displays a quick help message based on the input string.
	 * @param input String input.
	 */
	public void generateQuickHelpMsg(String input) {
		LOG.trace("Generating quick help for string " + input);
		QuickHelp.getInstance().generateQuickHelp(input);
	}
}
